from __future__ import annotations

import argparse
from pathlib import Path

from agent_society.governance.tasks import add_comment, create_task, list_tasks, update_status


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Governance task workflow CLI")
    parser.add_argument("event_dir", type=Path, help="Path to event log directory")
    subparsers = parser.add_subparsers(dest="command", required=True)

    create_parser = subparsers.add_parser("create", help="Create a governance task")
    create_parser.add_argument("owner")
    create_parser.add_argument("actor")
    create_parser.add_argument("title")
    create_parser.add_argument("description")
    create_parser.add_argument("--assignees", nargs="*", default=[])

    comment_parser = subparsers.add_parser("comment", help="Comment on a task")
    comment_parser.add_argument("owner")
    comment_parser.add_argument("actor")
    comment_parser.add_argument("task_id")
    comment_parser.add_argument("message")

    update_parser = subparsers.add_parser("update", help="Update task status")
    update_parser.add_argument("owner")
    update_parser.add_argument("actor")
    update_parser.add_argument("task_id")
    update_parser.add_argument("status")

    list_parser = subparsers.add_parser("list", help="List tasks")
    list_parser.add_argument("owner")
    list_parser.add_argument("--assignee")
    list_parser.add_argument("--status")

    return parser.parse_args()


def main() -> None:
    args = parse_args()
    base_dir = Path(args.event_dir)
    base_dir.mkdir(parents=True, exist_ok=True)

    if args.command == "create":
        event = create_task(base_dir, args.owner, args.actor, args.title, args.description, args.assignees)
        print(event.id)
    elif args.command == "comment":
        event = add_comment(base_dir, args.owner, args.actor, args.task_id, args.message)
        print(event.id)
    elif args.command == "update":
        event = update_status(base_dir, args.owner, args.actor, args.task_id, args.status)
        print(event.id)
    elif args.command == "list":
        tasks = list_tasks(base_dir, args.owner, assignee=args.assignee, status=args.status)
        for task in tasks:
            assignees = task.assignees or "-"
            print(f"{task.id} [{task.status}] {task.title} assignees={assignees} created={task.created_at}")
    else:
        raise SystemExit("Unknown command")


if __name__ == "__main__":
    main()
